package com.ecoolex.ying.space.core.manager;

import com.ecoolex.framework.common.util.Check;
import com.ecoolex.ying.space.core.dao.PushMessageReadStateDAO;
import com.ecoolex.ying.space.entity.PushMessageReadState;
import com.ecoolex.ying.space.entity.PushMessageReadState.Column;
import com.ecoolex.ying.space.entity.PushMessageReadStateExample;
import com.ecoolex.ying.space.entity.PushMessageReadStateExample.Criteria;

import java.time.Instant;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class PushMessageReadStateManager {

    @Autowired
    private PushMessageReadStateDAO dao;

    public boolean update(Integer readUserId,Integer releaseUserId, String updateUser) {
        PushMessageReadState pushMessageReadState = getByReadUserId(readUserId,releaseUserId);
        if(Check.isNull(pushMessageReadState)) {
        	pushMessageReadState = create(readUserId,releaseUserId,updateUser);
        }
        pushMessageReadState.setNewReadTime(Date.from(Instant.now()));
        pushMessageReadState.setUpdateUser(updateUser);
        pushMessageReadState.setUpdateTime(Date.from(Instant.now()));
        return dao.updateByPrimaryKeySelective(pushMessageReadState,
            Column.newReadTime,
            Column.updateUser,
            Column.updateTime) == 1;
    }

    public PushMessageReadState getByReadUserId(Integer readUserId,Integer releaseUserId) {
    	PushMessageReadStateExample example = new PushMessageReadStateExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andReadUserIdEqualTo(readUserId).andReleaseUserIdEqualTo(releaseUserId).andDeletedEqualTo(PushMessageReadState.NOT_DELETED);
        return dao.selectOneByExample(example);
    }

    public PushMessageReadState create(Integer readUserId,Integer releaseUserId, String createUser) {
        PushMessageReadState pushMessageReadState = new PushMessageReadState();
        pushMessageReadState.setReadUserId(readUserId);
        pushMessageReadState.setReleaseUserId(releaseUserId);
        pushMessageReadState.setNewReadTime(Date.from(Instant.now()));
        pushMessageReadState.setDeleted(PushMessageReadState.NOT_DELETED);
        pushMessageReadState.setCreateUser(createUser);
        pushMessageReadState.setCreateTime(Date.from(Instant.now()));
        pushMessageReadState.setUpdateUser(createUser);
        pushMessageReadState.setUpdateTime(Date.from(Instant.now()));
        dao.insert(pushMessageReadState);
        return pushMessageReadState;
    }
}